<template>
  <a-tree-select
    allow-clear
    style="width: 100%"
    :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
    placeholder="请选择平台"
    :value="modelValue"
    :treeData="treeData"
    :field-names="{
      label: 'title',
      value: 'userCode',
      key: 'userCode',
    }"
    @change="onChange"
    :multiple="multiple"
    :tree-checkable="multiple"
    :disabled="disabled"
  />
</template>
<script lang="ts" setup>
  import { ref, defineProps, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';

  const props = defineProps({
    modelValue: { type: [String, Number, Array], default: undefined },
    parentValue: { type: [String, Number, Array], default: '' },
    disabled: { type: Boolean, default: false },
    multiple: { type: Boolean, default: false },
    suportArea: { type: Boolean, default: false },
  });
  const emit = defineEmits(['update:modelValue', 'update:parentValue']);
  //树形下拉数据
  const treeData = ref<any[]>([]);
  //选择数据
  // const treeValue = ref<any>(null);
  onMounted(() => {
    loadTreeData();
  });
  /**
   * 选中树节点事件
   */
  function onChange(value) {
    // if (!value) {
    //   emit('update:modelValue', value);
    // } else if (value instanceof Array) {
    //   emit('update:modelValue', value);
    // } else {
    //   emit('update:modelValue', value);
    // }

    console.log('ppppp-----onChange', value);
    // treeValue.value = value;
    // 如果value是数组
    if (value instanceof Array) {
      const { parentNodes } = findParents(treeData.value, value);
      console.log('ppppp-----onChange----parentNodes', parentNodes);
      emit('update:parentValue', parentNodes);
    } else {
      const { parentNode } = findParentNode(treeData.value, value);
      if (parentNode) {
        console.log('parentNode', parentNode);
        emit('update:parentValue', parentNode.userCode);
      }
    }

    emit('update:modelValue', value);
  }

  // 从二级树形结构treeData，查找出所有父级。参数：id数组nodeIds，treeData
  function findParents(treeData, nodeIds) {
    let parentNodes: Set<any> = new Set();
    let noParentError = '';
    treeData.forEach((item) => {
      if (nodeIds.indexOf(item.userCode) > -1) {
        noParentError = `请选择${item.title}下面的子节点`;
      }
      if (item.children && item.children.length > 0) {
        for (let i = 0; i < item.children.length; i++) {
          const child = item.children[i];
          if (nodeIds.indexOf(child.userCode) > -1) {
            parentNodes.add(item.userCode);
            break;
          }
        }
      }
    });
    return {
      parentNodes,
      noParentError,
    };
  }
  async function loadTreeData() {
    let params = {
      async: false,
      pcode: 'B04',
    };
    let result = await defHttp.get({ url: '/sys/category/loadTreeRoot', params });
    console.log('loadTreeData', result);
    // 遍历树结构result 删除key。组件要求key与value一致
    result.forEach((item) => {
      delete item.key;
      if (!props.multiple && !props.suportArea) {
        item.disabled = true;
      }

      if (item.children && item.children.length > 0) {
        item.children.forEach((child) => {
          delete child.key;
        });
      }
    });
    // 设置树结构默认展开
    if (props.multiple) {
      treeData.value = [
        {
          children: [...result],
          title: '全部平台',
          key: 'all',
          userCode: 'all',
          value: null,
        },
      ];
    } else {
      treeData.value = [
        {
          title: '全部平台',
          key: 'all',
          userCode: 'all',
          value: null,
        },
        ...result,
      ];
    }
  }
  // 找到子节点的父级节点
  function findParentNode(treeData, nodeId) {
    let parentNode = null;
    let selfNode = null;
    let noParentError = '';
    treeData.forEach((item) => {
      if (item.userCode === nodeId) {
        noParentError = `请选择${item.title}下面的子节点`;
      }
      if (item.children && item.children.length > 0) {
        for (let i = 0; i < item.children.length; i++) {
          const child = item.children[i];
          if (child.userCode === nodeId) {
            parentNode = item;
            selfNode = child;
            break;
          }
        }
      }
    });
    return {
      parentNode,
      selfNode,
      noParentError,
    };
  }
</script>

<!-- <template>
    <CustomComponent v-model="message" />
  </template>
   
  <script>
  import CustomComponent from './CustomComponent.vue';
   
  export default {
    components: {
      CustomComponent,
    },
    data() {
      return {
        message: '',
      };
    },
  };
  </script> -->
